package com.gla.market.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gla.market.Listener.BaseUIListener;
import com.gla.market.entity.User;
import com.lidroid.xutils.util.LogUtils;
import com.gla.market.R;
import com.gla.market.constant.Constants;
import com.gla.market.utils.NetUtil;
import com.tencent.tauth.Tencent;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import static com.tencent.connect.common.Constants.*;
/**
 * 登录界面Activity
 */

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private static final int REQUEST_SIGNUP = 0;

    private String account = "";
    private String password = "";
    private User user;

    //绑定操作
    private EditText _mobile_Text;
    private EditText _passwordText;
    private Button _loginButton;
    private TextView _signupLink;
    private TextView back;
    private Button qq_login;
    //Tencent
    private Tencent mTencent;
    BaseUIListener baseUIListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        baseUIListener = new BaseUIListener(this);
        //初始化控件
        init();

        //登录按钮点击事件
        _loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(validate()){
                    login();
                }
            }
        });

        //注册按钮点击事件
        _signupLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
                startActivityForResult(intent, REQUEST_SIGNUP);
                finish();
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        qq_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        //初始化qq SDK
        Tencent.setIsPermissionGranted(true);
        qq_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                qqLogin();
            }
        });

    }
    private void init() {
        _mobile_Text = findViewById(R.id.input_mobile);
        _passwordText = findViewById(R.id.input_password);
        _loginButton = findViewById(R.id.btn_login);
        _signupLink = findViewById(R.id.link_signup);
        back = findViewById(R.id.back);
        qq_login = findViewById(R.id.btn_qq_login);
    }
    public void qqLogin()
    {
        mTencent = Tencent.createInstance("102011855", this.getApplicationContext(), "com.tencent.sample.fileprovider");
        HashMap<String, Object> params = new HashMap<String, Object>();
        if (!mTencent.isSessionValid())
        {
            params.put(KEY_SCOPE, "all");
            params.put(KEY_QRCODE, true);
            params.put(KEY_ENABLE_SHOW_DOWNLOAD_URL, true);
            mTencent.login(this, baseUIListener,params);
        }
    }

    /**
     * 登录
     */
    public void login() {

        account = _mobile_Text.getText().toString();
        password = _passwordText.getText().toString();
        loginRequest(account, password);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_SIGNUP) {
            if (resultCode == RESULT_OK) {
                this.finish();
            }
        }
    }


    /**
     * 成功登录的情况
     */
    public void onLoginSuccess(String message) {
        Toast.makeText(getBaseContext(), "登录成功!", Toast.LENGTH_LONG).show();
        _loginButton.setEnabled(true);
        SharedPreferences sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE); //私有数据
        //获取SharedPreferences编辑器
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("account", account);
        editor.putString("password", password);
        editor.putString("name", user.getName());
        editor.putInt("user_id", user.getId());
        System.out.println("登录成功，id："+user.getId());
        editor.putString("token",user.getToken());
        editor.putInt("is_vip",user.getIs_vip());
        editor.putString("photo",user.getPhoto());
        editor.commit();//提交修改

        Intent intent = new Intent();
        intent.putExtra("login", true);
        setResult(0,intent);
        finish();
    }

    /**
     * 登录失败的情况
     */
    public void onLoginFailed(String message) {
        Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
        _loginButton.setEnabled(true);
    }

    /**
     * 验证方法
     *
     * @return true/false 合法/非法
     */
    public boolean validate() {
        boolean valid = true;

        String email = _mobile_Text.getText().toString();
        String password = _passwordText.getText().toString();

        if (email.isEmpty()) {
            _mobile_Text.setError("请输入有效账号");
            valid = false;
        } else {
            _mobile_Text.setError(null);
        }

        if (password.isEmpty() || password.length() < 3) {
            _passwordText.setError("请输入3位以上的密码");
            valid = false;
        } else {
            _passwordText.setError(null);
        }

        return valid;
    }

    /**
     * 根据handler结果进行不同操作
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    onLoginSuccess(msg.obj.toString());
                    break;
                default:
                    onLoginFailed(msg.obj.toString());
                    break;
            }
        }
    };

    /**
     * 使用账号密码登录
     * @param password 密码
     */
    private void loginRequest(String account, String password) {

        String url = Constants.BASE_URL + Constants.LOGIN_URL + "?account="+account+"&password="+password;
        NetUtil.doGet(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = Message.obtain();
                message.what = -1;
                handler.sendMessage(message);
                Log.e("登录失败！", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui

                Message message = Message.obtain();
                try {
                    String jsonStr = response.body().string().trim();
                    JSONObject json = JSON.parseObject(jsonStr);
                    Log.i("调试", "登录成功"+jsonStr);
                    if (json.getInteger("code")==100) {
                        //拿到userId
                        JSONObject getuser = json.getJSONObject("data");
                        user = new User();
                        user.setId(getuser.getIntValue("id"));
                        user.setAccount(getuser.getString("account"));
                        user.setName(getuser.getString("name"));
                        user.setPhoto(getuser.getString("photo"));
                        user.setIs_vip(getuser.getInteger("is_vip"));
                        user.setToken(getuser.getString("token"));

                        message.what = 1;
                        message.obj = json.getString("message");
                    } else {
                        message.what = 0;
                        message.obj = json.getString("message");
                    }
                } catch (Exception e) {
                    //String jsonStr2 = response.body().string().trim();
                    LogUtils.e("用户信息"+e.getMessage());
                    if (e instanceof NullPointerException) {
                        Log.e("network error!", e.getMessage());
                    }
                    message.what = 0;
                    message.obj = "登陆失败！";
                }

                handler.sendMessage(message);
            }
        });
    }

}
